<template>
    <div class="content">
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :model="formInline" class="formInline" label-width="70px" slot="form" label-position="right">
                  <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="学校名称" >
                          <el-select :disabled="true" v-model="getSchool" filterable remote clearable reserve-keyword placeholder="请输入学校名称" :remote-method="remoteMethod" :loading="loading" style="width:100%" @change="queryAllGrade( getSchool )">
                            <el-option v-for="item in schoolList" :key="item.schoolId" :label="item.schoolName" :value="item.schoolName">
                            </el-option>
                          </el-select>
                        </el-form-item>
                    </el-col>
                    
                    <el-col :span="8">
                        <el-form-item label="班主任">
                          <el-input v-if="roleType=='5'" v-model="sUserName" :disabled="true" :maxlength="30" :placeholder="teacherName" style="width:100%;"></el-input>
                          <el-input v-else v-model="sUserName" :maxlength="30" placeholder="请输入查询的名称" style="width:100%;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="年级" v-if="train">
                            <el-select v-model="getGradeName" placeholder="请选择查询的年级" style="width:100%;" :disabled="isClassNum" @change="queryAllClass( getGradeName )">
                              <el-option v-for="item in gradeList" :key="item.grade" :label="item.gradeName" :value="item.grade">
                              </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="班级编号" v-if="!train">
                            <el-select v-model="classNum" placeholder="请选择查询的班级编号" style="width:100%;" @change="classChange" >
                              <el-option v-for="(item,index) in classList" :key="index" :label="item.sClassNum" :value="item.pId" >
                              </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="41">
                    
                    <el-col :span="8">
                      <el-form-item label="班级编号" v-if="train">
                            <el-select v-model="classNum" placeholder="请选择查询的班级编号" style="width:100%;" @change="classChange" >
                              <el-option v-for="(item,index) in classList" :key="index" :label="item.sClassNum" :value="item.pId" >
                              </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班级名称">
                          <el-input v-model="sNickName" :maxlength="30" placeholder="请输入查询的班级名称" style="width:100%;"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="top-line">
                  <!-- class="btnPosition" -->
                    <div class="top-line"> 
                        <el-button type="primary" @click="onSubmit">查询</el-button>
                    </div>
                </div>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button @click="addClass" v-if="roleType!='5'">添加班级</el-button>
                    <el-button @click="exportClass">班级导出</el-button>
                </div>
            </div>
            <el-table :data="dataApply" style="width: 100%" v-loading="loading" border>
                <el-table-column label="班级名称" align="center">
                  <template scope="scope">
                    {{ scope.row.className | isNull}}
                  </template>
                </el-table-column>

                <el-table-column label="班级编号" align="center">
                  <template scope="scope">
                    {{scope.row.classNum | isNull}}
                  </template>
                </el-table-column>

                <el-table-column label="年级" align="center">
                  <template scope="scope">
                    {{scope.row.gradeName | isNull}}
                  </template>
                </el-table-column>

                <el-table-column label="学生数量" align="center">
                  <template scope="scope">
                    <el-button type="text" class="btn-success" @click="btnStudentData(scope.row)" >{{!scope.row.num ? '0' : scope.row.num}}</el-button>
                  </template>
                </el-table-column>

                <el-table-column v-if="roleType!='5'" label="班主任" align="center">
                  <template scope="scope">
                    {{ scope.row.ownerName | isNull}}
                  </template>
                </el-table-column>

                <el-table-column label="班级码" align="center">
                  <template scope="scope">
                    {{scope.row.classCode | isNull}}
                  </template>
                </el-table-column>

                <el-table-column label="其他操作" width="200">
                    <template scope="scope">
                        <el-button type="text" class="btn-success" @click="classDetails(scope.row)" >班级详情</el-button>
                        <el-button type="text" class="btn-success" @click="delClass(scope.row)" >删除</el-button>
                        <!-- 0禁用 1启用 -->
                        <el-button type="text" class="btn-success" @click="betProhibit(scope.row.classId,scope.row.status,scope.row)"  v-cloak>{{scope.row.status == 1 ? '禁用' : '启用'}}</el-button>
                    </template>
                </el-table-column>

            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total" :current-page.sync="listQuery.page" :page-sizes="config.pageSizes" :page-size="config.pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
        <!-- 添加班级 -->
        <addClassSchool @addClassState="addClassState" v-if="addClassMain.dialogFormVisible" :addClassMain="addClassMain"></addClassSchool>
    </div>
</template>

<script>
import {
  getclassAll,
  classListData,
  deleteClass,
  getSchoolList,
  getGrade,
  getClass,
  getOwnerList,
  getClassName,
  groupChart
} from "api/classAll";
import TableLayout from "components/TableLayout";
import { mapState, mapActions, mapGetters } from "vuex";
import headmasterData from "./headmasterData";
import addClassSchool from "./addClassSchool";
import province from "components/CascadeRegion/province";
import city from "components/CascadeRegion/city";
import region from "components/CascadeRegion/region";
import Cookies from "js-cookie";
// Cookies.get('userType'),
export default {
  name:"classAll",
  components: {
    TableLayout,
    headmasterData,
    addClassSchool,
    province,
    city,
    region
  },
  data() {
    return {
      listQuery: {
        //分页
        page: 1,
        total: 0
      },

      //添加班级-子组件
      addClassMain: {
        dialogFormVisible: false,
        className:'',
        schoolType:''
      },

      //查询所有数据集合
      formInline: {},
      loading: true,

      //table数组集合
      dataApply: [],

      //省市区三个集合
      allCity: {
        province: [],
        cityList: [],
        CountyList: []
      },

      //学校集合
      schoolList: [],

      //年级集合
      gradeList: [],

      //班级编辑集合
      classList: [],

      //班主任集合
      // ownerNameList: [],

      //班级名称集合
      classNameArray: [],

      //获取学校名称
      getSchool: "",

      //获取班主任
      sUserName: "",

      //获取年级
      getGradeName: "",

      //获取班级编号
      classNum: null,

      //获取学校id
      newSchoolId: "",

      //班级名称
      sNickName: "",

      //判断班级编号是否为空
      isClassNum: false,

      //新的班级编号
      newClassNum: "",
      //培训学校
      train: true,
      disabled: false
    };
  },
  computed: {
    ...mapState({
      config: state => state.config.table,
      cacheUpdated: state => state.app.cacheUpdated// 局部刷新列表
    }),
    ...mapGetters(["uid", "schoolId", "schoolName", "schoolType", "roleType", "teacherName","token"])
  },
  //初始化
  created() {
    if (this.schoolType == "null" || this.schoolType == "1") {
      //当前的id传过去
      getClassName(this.schoolId).then(response => {
        this.classList = response.data.content;
        if (this.classList) {
          this.classList.unshift({ sClassNum: "请选择", sNickName: "" });
        }
      });
      this.getSchool = this.schoolName;
      //不能输入
      this.train = false;
    } else {
      this.getSchool = this.schoolName;
      this.train = true;
      this.queryAllGrade(this.schoolId);
    }

    //判断是否显示隐藏班主任
    if(this.roleType=='5'){
      this.sUserName = this.teacherName;
    }
    this.searchFetchData();
  },
  watch: {// 局部刷新列表
        cacheUpdated(val) {
            val=='2' && this.searchFetchData();
        }
    },
  methods: {
    ...mapActions(["ChangePageSize"]),
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //分页
    handleSizeChange(val) {
      this.loading = true;
      this.listQuery.page = 1;
      this.ChangePageSize(val);
      this.searchFetchData();
    },
    handleCurrentChange(val) {
      this.loading = true;
      this.listQuery.page = val;
      this.searchFetchData();
    },
    //模糊查询学校名称
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        //每次都清除上一次
        this.sNickName = "";
        this.classNum = "";
        // this.classList = [];
        setTimeout(() => {
          this.loading = false;
          getSchoolList(query).then(response => {
            this.schoolList = response.data.content;
            this.getSchoolList = "";
          });
        }, 200);
      } else {
        this.getSchool = "";
        this.sNickName = "";
        this.classNum = "";
        // this.classList = [];
      }
    },
    // 年级列表
    queryAllGrade(schoolId) {
      if (!schoolId) {
        return false;
      } else {
        this.getGradeName = "";
        this.newSchoolId = schoolId;
        getGrade(!schoolId ? null : schoolId).then(response => {
          this.gradeList = response.data.content;
          this.gradeList.unshift({ gradeName: "请选择年级", gradeId: "" });
        });
      }
    },
    //通过学校名称 查询学校id
    getSchoolId(val) {
      let id = "";
      this.schoolList.forEach(item => {
        if (val == item.schoolName) {
          id = item.schoolId;
        }
      });
      return id;
    },
    classChange(cid) {
      if (!cid) {
        // this.classList = [];
        this.sNickName = "";
        this.newClassNum = "";
        return false;
      } else {
        //获取lable的值
        this.newClassNum = "";
        let obj = this.classList.find(item => {
          return item.pId === cid;
        });
        this.newClassNum = obj.sClassNum;

        //判断是否选择了年级
        if (this.getGradeName) {
          // this.sNickName =
          //   this.getGradeNameFn() + "(" + this.getClassNum(cid) + ")班";
          this.classList.find(item => {
            if (cid === item.pId) {
              this.sNickName = item.sNickName;
            }
          });
        } else {
          this.classList.find(item => {
            if (cid === item.pId) {
              this.sNickName = item.sNickName;
            }
          });
        }
      }
    },
    nameChange(cid) {
      if (this.getClassNum(cid)) {
        this.classNum = cid;
      }
    },
    getGradeNameFn() {
      var gn = "";
      if (!this.gradeList) {
        return false;
      } else {
        this.gradeList.forEach(g => {
          if (g.gradeId === this.getGradeName) {
            gn = g.gradeName;
          }
        });
      }
      return gn;
    },
    getClassNum(cid) {
      var cn = "";
      if (!this.classList) {
        return false;
      } else {
        this.classList.forEach(c => {
          if (c.pId == cid) {
            cn = c.sClassNum;
          }
        });
      }
      return cn;
    },
    // 班级列表
    queryAllClass(gradeId) {
      if (gradeId) {
        this.classNum = "";
        this.sNickName = this.getGradeNameFn();
        getClassName(
          !this.newSchoolId ? null : this.newSchoolId,
          !gradeId ? null : gradeId
        ).then(response => {
          this.classList = response.data.content;
          this.classList.unshift({sClassNum:"请选择"})
        });
      } else {
        //duidui
        this.classNum = "";
        this.sNickName = "";
        this.classList = [];
      }
    },
    //模糊查询班级名称
    queryAllClassName(val) {
      if (val !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          getClassName(
            !this.newSchoolId ? null : this.newSchoolId,
            !this.getGradeName ? null : this.getGradeName,
            !this.classNum ? null : this.classNum,
            null
          ).then(data => {
            this.classNameArray = data.content;
          });
        }, 200);
      } else {
        this.sNickName = "";
      }
    },
    //查询列表
    searchFetchData() {
      this.loading = true;
      classListData(
        !this.sUserName ? null : this.sUserName,
        !this.getGradeName ? null : this.getGradeName,
        !this.sNickName ? null : this.sNickName,
        !this.newClassNum ? null : this.newClassNum,
        !this.schoolId ? this.schoolId : this.schoolId,
        this.listQuery.page,
        this.config.pageSize
      ).then(response => {
        this.loading = false;
        if (!response.data.content) {
          this.dataApply = [];
          this.listQuery.total = 0;
        } else {
          this.dataApply = response.data.content.list;
          this.listQuery.total = response.data.content.pagination.total;
        }
      });
    },
    //导出
    exportClass(){
      
      // //console.log(`this.schoolId=${this.schoolId},this.sUserName=${this.sUserName}this.getGradeName=${this.getGradeName || ''}this.sNickName=${this.sNickName}this.newClassNum=${this.newClassNum}this.token=${this.token}`)
      window.location.href = `${LOCAL_API.ly}/eduClass/exportClassByCondition?ownerName=${this.sUserName}&grade=${this.getGradeName || ''}&className=${this.sNickName}&classNum=${this.newClassNum}&schoolId=${this.schoolId}&token=${this.token}`
    },
    //表单查询
    onSubmit() {
      this.loading = true;
      this.listQuery.page = 1;
      this.searchFetchData();
    },
    addClass() {
      let id = "";
      this.schoolList.forEach(item => {
        if (this.getSchool == item.schoolName) {
          id = item.schoolId;
        }
      });
      this.addClassMain.dialogFormVisible = true;
      this.addClassMain.getSchool = this.getSchool;
      this.addClassMain.state = this.schoolType;
      this.addClassMain.schoolId = id;
    },
    // 点击学生数量
    btnStudentData(val) {
      this.$router.push({ path: `/classStudent/studentList/${val.classId}`});
      this.$store.dispatch('UpdateCache',true);
    },
    delClass(val) {
      //判断学生数量是否等于0
      if (val.num !== "0" && val.num !== null) {
        this.$message({
          type: 'info',
          message: "需要删除所有学生才能删除班级哦~"
          // type: "warning"
        });
      } else {
        this.$confirm("确定删除该班级, 是否继续?", " ", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
          // type: "warning"
        })
          .then(() => {
            this.loading = true;
            deleteClass(val.classId)
              .then(data => {            
                if (this.roleType=='5' && this.dataApply.length<2){
                    this.loading = false;
                    this.$message({                                    
                        message: '用户被禁用,即将退出登陆！',
                        type: 'error'
                    });
                    setTimeout(() => {
                        this.$store.dispatch('FedLogOut').then(() => {
                            location.reload(); // 为了重新实例化vue-router对象 避免bug
                        });
                    }, 3000);
                    return
                } else {
                    this.$message({
                      type: "success",
                      message: "删除成功!"
                    });
                }
                this.searchFetchData();
              })
              .catch(error => {
                this.loading = false;
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },
    betProhibit(val, sta, num) {
      //判断学生数量是否为空
      if (num.num > 0) {
        // 0 禁用
        if (sta == 0) {
          this.$confirm('是否启用群聊', ' ', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ' '
        }).then(() => {
          groupChart(val, 1).then(data => {
            this.$message({
              message: "设置成功！",
              type: "success"
            });
            this.searchFetchData();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });

        } else {
          this.$confirm('是否禁用群聊', ' ', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ' '
        }).then(() => {
          groupChart(val, 0).then(data => {
            this.$message({
              message: "设置成功！",
              type: "success"
            });
            this.searchFetchData();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
        }
      } else {
        this.$message({
          message: "该班级目前不支持群聊",
          type: "warning"
        });
      }
    },
    classNewName(val) {
      if (!val) {
        // //console.log("没有修改");
      } else {
        //发现传递过来数据，刷新父组件的数据
        this.searchFetchData();
      }
    },
    addClassState(val) {
      if (!val) {
      } else {
        //从新发送请求
        this.listQuery.page = 1;
        this.sUserName = '';
        this.getGradeName = '';
        this.sNickName = '';
        this.newClassNum = '';
        this.searchFetchData();
      }
    },
    // 点击班级详情
    classDetails(val){
      this.$router.push({ path: `/classStudent/classDetails/${val.classId}`});
      this.$store.dispatch('UpdateCache',true);
    }
  }
};
</script>
<style lang="scss" scoped>
.content {
  position: relative;
  padding: 0px;
  $bgcolor: #fff;
  .formInline {
    .formBtn {
      width: 100%;
      height: 70px;
      border-top: 1px solid #dddddd;
      position: relative;
      .btnPosition {
        position: absolute;
        right: 0px;
        top: 18px;
      }
    }
  }
}
</style>